package com.example.chesswithnet.Demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String args[]) throws IOException {
        // 创建服务器，并启动，给服务器绑定一个端口号
        ServerSocket server = new ServerSocket(8080);
        System.out.println("服务器连接成功");
        // 一直等待客户端来连接
        while (true){
            // 等待客户端来连接，accept代表已经成功连接上服务器客户Socket对象
            Socket accept = server.accept();
            System.out.println(accept);
            // 读取客户端的信息，通过IO流，输入流进行读取
            InputStream is = accept.getInputStream();
//            byte[] bytes = is.readAllBytes();   //一次性读完
            byte[] bytes = new byte[1024];
            int len = is.read(bytes);  // 将数据读取到bytes数据中，并返回实际读取的长度，当读完后返回-1
//            System.out.println("对方说"+new String(bytes,"UTF-8"));
            System.out.println("对方说"+new String(bytes,0,len,"UTF-8"));
            write(accept, "这是服务端，已经收到消息，over");  //回信
            accept.shutdownOutput(); // 关闭输出流，只能发送一次
        }
    }

    public static void write(Socket accept, String message) throws IOException {
        OutputStream os = accept.getOutputStream();
        os.write(message.getBytes());
    }

}
